package cc.fs.zhihuapp.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import cc.fs.zhihuapp.R;

/**
 * Created by fostion on 2015/9/10.
 */
public class SwipeBackLayout extends RelativeLayout {

    private ViewDragHelper mViewDragHelper;
    private View mContentView;
    private int mContentWidth;
    private int mMoveLeft;
    private boolean isClose = false;
    private boolean isDrag;
    private DragCallBack mDragCallBack;

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        //方式1获取属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayoutAttr);
        isDrag = a.getBoolean(R.styleable.SwipeBackLayoutAttr_isDrag, true);
        a.recycle(); // 回收资源
        if (isDrag) {
            setUpViewDragHelper();
        }
    }

    public void setUpViewDragHelper() {
        mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {

            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return child == mContentView;//只有第一个子view才可以移动
            }

            /**
             * 记录向左移动的值
             */
            @Override
            public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
                mMoveLeft = left;
                if (isClose && (left == mContentWidth)) {
                    //如果当前状态是关闭状态且左边的值等于滑动的View的宽度，
                    //也就是说当前的界面已经滑出屏幕，就回调finish方法，通知activity可以finish了
                    if (mDragCallBack != null) {
                        mDragCallBack.onDrag();
                    }
                }
            }

            /**
             * 手指释放view触发效果：
             * 若是距离不够就弹回去
             */
            @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                //借助computeScroll方法 移动距离大于四分之一将会关闭否则弹回
                if (mMoveLeft >= (mContentWidth / 4)) {
                    //划出屏幕
                    isClose = true;
                    mViewDragHelper.settleCapturedViewAt(mContentWidth, releasedChild.getTop());
                } else {
                    //返回原来位置
                    isClose = false;
                    mViewDragHelper.settleCapturedViewAt(0, releasedChild.getTop());
                }
                invalidate();
            }

            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                return Math.min(mContentWidth, Math.max(left, 0));
            }

            @Override
            public int getViewHorizontalDragRange(View child) {
                return mContentWidth;
            }
        });
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() != 1) {
            throw new IllegalStateException("SwipeBackLayout only have one child view");
        }
        mContentView = getChildAt(0);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mContentWidth = mContentView.getWidth();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.e("  -- ", mViewDragHelper.shouldInterceptTouchEvent(ev) + "  ");
        return mViewDragHelper != null ? mViewDragHelper.shouldInterceptTouchEvent(ev) : super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mViewDragHelper != null) {
            mViewDragHelper.processTouchEvent(event);
        }
        return true;
    }

    /**
     * 根据抬手后的位置滑动到需要滑动的位置
     */
    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
            invalidate();
        }
    }

    public void setCanDrag(boolean isDrag) {
        this.isDrag = isDrag;
        setUpViewDragHelper();
    }

    public void setDragCallBack(DragCallBack mDragCallBack) {
        this.mDragCallBack = mDragCallBack;
    }

    public interface DragCallBack {
        void onDrag();
    }
}
